﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MINERP.MODEL.Statistics;
using MINERP.BLL.Statistics;
using MINERP.DAL;
using MINERP.COM;
using FastReport;
using System.IO;

namespace MINERP.Statistics
{
    public partial class FrmSalesmanPay : Form
    {
        private static FrmSalesmanPay _instance = null;
 
        private Salesman_Info _salesman = null;

        FinanceBLL _bll = new FinanceBLL();


        private decimal _blance = 0;         // 帐户余额
        public decimal blance { get { return _blance; } set { _blance = value; CanCheckOutMoney = (double)value + _arrearageCount; } }// 帐户余额



        private double _CanCheckOutMoney = 0;//能够抵冲的金额
        public double CanCheckOutMoney { get { return _CanCheckOutMoney; } set { _CanCheckOutMoney = value; lblCanCheckOutMoney.Text = _CanCheckOutMoney.ToString("0.00"); } }

        private double _arrearageCount;//欠款总额
        public double ArrearageCount { get { return _arrearageCount; } set { _arrearageCount = value; CanCheckOutMoney = value + (double)_blance; txtAllNeedPayBill.Text = _arrearageCount.ToString("0.00"); } }


        private decimal _allBillCount;      //将要抵冲的金额
        public decimal allBillCount { get { return _allBillCount; } set { _allBillCount = value; txtAllBillMoney.Text = value.ToString("0.00"); } }

        private FrmSalesmanPay(Salesman_Info salesman)
        {
            InitializeComponent();
            _salesman = salesman;
        }
        public static FrmSalesmanPay GetInstance(Salesman_Info salesman)
        {
            if (_instance == null)
            {
                _instance = new FrmSalesmanPay(salesman);
            }
            return _instance;
        }

        private void cmbShop_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {

        }

        private void FrmSalesmanPay_Load(object sender, EventArgs e)
        {
            txtClearMoney.Text = "0";

            gridControlOrderBag.Visible = false;
            gridControlBill.Visible = true;

            gridControlBill.DataSource = _bll.GetSalesmanBillList(_salesman);
            CountAllBillNeedPay();
           
            RefreshStatus();
            LinkSalesman();
            cmbSalesman.Text =_salesman.SalesmanName;
        }

        private void CountAllBillNeedPay()
        {
            double AllBillNeedPay = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = new BillEntity();
                billEntity = (BillEntity)gridViewBill.GetRow(i);
                AllBillNeedPay += billEntity.NoPayBillCount;
            }
            //CanCheckOutMoney = (double)blance + AllBillNeedPay;
            ArrearageCount = AllBillNeedPay;
            //lblCanCheckOutMoney.Text = Math.Round(blance + (decimal)AllBillNeedPay, 2).ToString();
            //txtAllNeedPayBill.Text = Math.Round(AllBillNeedPay, 2).ToString();
        }

        public void LinkSalesman()
        {
            foreach (var item in _bll.GetSalesmanInfoList())
            {
                cmbSalesman.Properties.Items.Add(item.SalesmanName.ToString());
            }
        }

        public void RefreshStatus()
        {
            if (_salesman.Balance != null)
            {
                blance = Math.Round((decimal)_salesman.Balance, 2);
            }

            tssSalesman.Text = _salesman.SalesmanName;
            tssBlance.Text = blance.ToString();

        }

        private void FrmSalesmanPay_FormClosed(object sender, FormClosedEventArgs e)
        {
            _instance = null;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Shop shop = null;                
            if (txtMoney.Text != string.Empty && Convert.ToDecimal(txtMoney.Text) != 0)
            {
                if (DialogResult.OK == MessageBox.Show("确定冲值" + txtMoney.Text + "元吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                    {
                        if (db.Connection.State != System.Data.ConnectionState.Open)
                        {
                            db.Connection.Open();
                        }
                        System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                        SalesmanBalance curSalesman = db.SalesmanBalance.FirstOrDefault(s => s.SalesmanId ==_salesman.SalesmanId);
                        shop = db.Shop.FirstOrDefault(s => s.Salesman == _salesman.SalesmanName);
                        if (curSalesman != null)
                        {
                            if (curSalesman.Balance != null)
                            {
                                curSalesman.Balance += Math.Round(Convert.ToDecimal(txtMoney.Text.Trim()), 4);
                            }
                            else
                            {
                                curSalesman.Balance = Math.Round(Convert.ToDecimal(txtMoney.Text.Trim()), 4);
                            }

                            _salesman.Balance = curSalesman.Balance;
                        }
                        db.SaveChanges();

                        //插入充值记录

                        string strRemark = "业务员充值";
                        if (!string.IsNullOrEmpty(txtRemark.Text.Trim()))
                        {
                            strRemark = txtRemark.Text.Trim();
                        }
                        ShopBlanceCrushRecord crushRecord = new ShopBlanceCrushRecord();
                        crushRecord.CrushMoney = Convert.ToDecimal(txtMoney.Text.Trim());
                        crushRecord.CrushTime = DateTime.Now;
                        crushRecord.Operator = FrmMain.loginName;
                        crushRecord.Shop = db.Shop.FirstOrDefault(s => s.ShopId == shop.ShopId);

                        crushRecord.Overage = (decimal)_salesman.Balance;
                        crushRecord.Remark = strRemark;
                        crushRecord.Operation = (int)CountOperationType.ChongZhi;

                        db.AddToShopBlanceCrushRecord(crushRecord);

                        db.SaveChanges();
                        tran.Commit();

                        PrintCrushBill(crushRecord.CrushMoney, crushRecord.Overage, crushRecord.Operator, crushRecord.CrushTime, _salesman.SalesmanName, crushRecord.Remark);
                    }

                    //string strRemark = "业务员充值";
                    //if (!string.IsNullOrEmpty(txtRemark.Text.Trim()))
                    //{
                    //    strRemark = txtRemark.Text.Trim();
                    //}

                    //CrushRecord(strRemark, Convert.ToDecimal(txtMoney.Text), CountOperationType.ChongZhi,shop);
                    //自动激活那些因为欠款而不能生产的产品
                    _bll.ActiveSalesmanOrder(_salesman);

                    RefreshStatus();
                    //frmFinance.LinkDataGrid();
                    txtMoney.Text = string.Empty;
                    MessageBox.Show("充值成功,充值金额：" + txtMoney.Text + " 元", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请输入充值金额", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtMoney.Focus();
            }
        }

        private void PrintCrushBill(decimal crushMoney, decimal overage, string oprator, DateTime crushtime, string shopName, string remark)
        {
            Report rpt = new Report();
            rpt.Load(Application.StartupPath + "\\Report\\CrushBill.frx");
            rpt.SetParameterValue("ShopName", shopName);
            rpt.SetParameterValue("CrushMoney", crushMoney);
            rpt.SetParameterValue("Overage", overage);
            rpt.SetParameterValue("CrushTime", crushtime);
            rpt.SetParameterValue("Oprator", oprator);
            rpt.SetParameterValue("Remark", remark);
            rpt.PrintSettings.ShowDialog = true;
            rpt.Print();

            rpt.Prepare();
            string excelPath = Application.StartupPath + "\\报表文件\\" + shopName;
            if (!Directory.Exists(excelPath))
            {
                Directory.CreateDirectory(excelPath);
            }
            string repPath = excelPath + "\\" + DateTime.Now.ToString().Replace(":", " ") + ".fpx";
            rpt.SavePrepared(repPath);
        }
        private void btnActiveOrder_Click(object sender, EventArgs e)
        {
            if (txtAllBillMoney.Text == string.Empty || !isAnyChecked())
            {
                MessageBox.Show("请选择要冲抵的账单！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            decimal money = allBillCount - Convert.ToDecimal(txtClearMoney.Text);//实际冲抵金额 
            if (DialogResult.OK == MessageBox.Show("确定冲抵以下选中帐单吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
               
                DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                List<BillEntity> selectedBill = ((List<BillEntity>)gridViewBill.DataSource).Where(b => b.IsChecked).ToList();
                if (selectedBill.Count < 1)
                {
                    return;
                }

                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    Shop shop = db.Shop.FirstOrDefault(s=>s.Salesman ==_salesman.SalesmanName);
                    foreach (var billInfo in selectedBill)
                    {
                        SHOP_Bill bill = db.SHOP_Bill.FirstOrDefault(b => b.BillId == billInfo.BillID);
                        
                        bill.Status = (int)ShopBillStatus.CheckedOut;
                        if (!bill.Bill_Detail.IsLoaded)
                        {
                            bill.Bill_Detail.Load();
                        }
                        foreach (var billDetail in bill.Bill_Detail)
                        {
                            billDetail.IsCheckOut = true;
                        }
                    }

                    CrushRecord("业务员冲抵账单", -money, CountOperationType.DiChong, shop);
                    if (txtClearMoney.Text != string.Empty && Convert.ToDecimal(txtClearMoney.Text) != 0)
                    {
                        CrushRecord("清零(" + txtClearRemark.Text + ")", -Convert.ToDecimal(txtClearMoney.Text), CountOperationType.QingLing, shop);
                    }
                    db.SaveChanges();
                }

                RefreshStatus();

                gridControlBill.DataSource = _bll.GetSalesmanBillList(_salesman);
                CountAllBillNeedPay();
                allBillCount = 0;
                txtAllBillMoney.Text = string.Empty;
                txtClearMoney.Text = "0";
            }
        }

        private void tsbtnSelectAll_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                allBillCount += (decimal)billEntity.NoPayBillCount;
            }
            if (CanCheckOutMoney >= (double)allBillCount)
            {
                allBillCount = 0;
                for (int i = 0; i < gridViewBill.RowCount; i++)
                {
                    BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                    billEntity.IsChecked = true;
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                }
                txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                gridViewBill.RefreshData();
            }
            else
            {
                allBillCount = 0;
                MessageBox.Show("帐户余额不足,不能全选，请逐条选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tsbtnFanXuan_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            List<BillEntity> list = new List<BillEntity>();
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if (!billEntity.IsChecked)
                {
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                }

            }
            if (CanCheckOutMoney >= (double)allBillCount)
            {
                allBillCount = 0;
                for (int i = 0; i < gridViewBill.RowCount; i++)
                {
                    BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                    if (!billEntity.IsChecked)
                    {
                        billEntity.IsChecked = true;
                        list.Add(billEntity);
                        allBillCount += (decimal)billEntity.NoPayBillCount;
                    }
                    else
                    {
                        billEntity.IsChecked = false;
                        list.Add(billEntity);
                    }
                }
                txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                gridControlBill.DataSource = list;
            }
            else
            {
                allBillCount = 0;
                MessageBox.Show("帐户余额不足,不能反选，请逐条选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            allBillCount = 0;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if ((decimal)CanCheckOutMoney >= (allBillCount + (decimal)billEntity.NoPayBillCount))//可抵冲
                {
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                    billEntity.IsChecked = true;
                }
            }

            gridViewBill.RefreshData(); 
        }

        private void CrushRecord(string type, decimal money, CountOperationType OperationType,Shop shop)
        {
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                ShopBlanceCrushRecord crushRecord = new ShopBlanceCrushRecord();
                crushRecord.CrushMoney = money;
                crushRecord.CrushTime = DateTime.Now;
                crushRecord.Operator = FrmMain.loginName;
                crushRecord.Shop = enty.Shop.FirstOrDefault(s=>s.ShopId==shop.ShopId);
                
                crushRecord.Overage = (decimal)_salesman.Balance;
                crushRecord.Remark = type;
                crushRecord.Operation = (int)OperationType;

                enty.AddToShopBlanceCrushRecord(crushRecord);
                enty.SaveChanges();

            }
        }

        private bool isAnyChecked()
        {
            bool flag = false;
            for (int i = 0; i < gridViewBill.RowCount; i++)
            {
                BillEntity billEntity = (BillEntity)gridViewBill.GetRow(i);
                if (billEntity.IsChecked)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        private void cmbSalesman_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            _salesman = _bll.GetSalesmanInfo(cmbSalesman.Text.Trim());
            RefreshStatus();
            gridControlBill.DataSource = _bll.GetSalesmanBillList(_salesman);
            gridViewBill.RefreshData();
            CountAllBillNeedPay();
        }

        private void gridViewBill_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            BillEntity billEntity = (BillEntity)gridViewBill.GetRow(e.RowHandle);
            if ((bool)e.Value)
            {
                //allBillCount += (decimal)billEntity.BillCount;
                //allBillCount = Math.Round(allBillCount,2);
                //if (allBillCount <= _shop.Balance + (txtClearMoney.Text == null ? 0 : Convert.ToDecimal(txtClearMoney.Text)))
                if ((double)allBillCount + billEntity.NoPayBillCount <= CanCheckOutMoney + (txtClearMoney.Text == null ? 0 : Convert.ToDouble(txtClearMoney.Text)))
                {
                    allBillCount += (decimal)billEntity.NoPayBillCount;
                    //txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                }
                else
                {
                    billEntity.IsChecked = false;
                    gridViewBill.RefreshData();
                    //allBillCount -= (decimal)billEntity.BillCount;
                    //txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
                    MessageBox.Show("可抵冲余额不足", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
            else
            {
                allBillCount -= (decimal)billEntity.NoPayBillCount;
                //txtAllBillMoney.Text = Math.Round(allBillCount, 2).ToString();
            }
        }



    }
}
